var db = require('../../db/db');
var publictool = require("../../publictool/publictool");

exports.port = function (req, res) {
    var requestData = '';
    req.addListener('data', function (postDataChunk) {
        requestData += postDataChunk;
    });

    req.addListener('end', function () {

        db.checksnnum()
            .then(function (isok) {
                if (isok) {
                    processEnd(res,req, requestData);
                } else {
                    publictool.returnErr(res, '数据库错误', 1);
                    return;
                }
            });
    });
};

function processEnd(res,req, requestData) {
    publictool.putlog(req, requestData);
    var phone = publictool.checkoutdata(res, requestData);
    if (!phone) {
        return;
    }

    var client = db.client();
    db.checkuser(client, res, true, phone.accesstoken)
        .then(function (resultvalue) {
            var addSql = 'INSERT INTO device(manager,sn) VALUES(?,?)';
            var addSqlParams = [resultvalue.account, phone.sn];
            client.query(addSql, addSqlParams, function (err, result) {
                if (err) {
                    publictool.returnErr(res, '插入参数错误:' + '[INSERT ERROR] - ' + err.message, 1);
                    client.end();
                    return;
                }

                publictool.returnErr(res, '操作成功', 0);
                client.end();
                return;
            });
        });
}